//package com.qujia.station.controller;
//
//import cn.afterturn.easypoi.excel.ExcelExportUtil;
//import cn.afterturn.easypoi.excel.entity.ExportParams;
//import com.google.zxing.BarcodeFormat;
//import com.google.zxing.EncodeHintType;
//import com.google.zxing.MultiFormatWriter;
//import com.google.zxing.common.BitMatrix;
//import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
//import com.qujia.common.annotation.Log;
//import com.qujia.common.core.controller.BaseController;
//import com.qujia.common.core.domain.AjaxResult;
//import com.qujia.common.core.domain.ResultData;
//import com.qujia.common.core.domain.model.LoginUser;
//import com.qujia.common.core.page.TableDataInfo;
//import com.qujia.common.core.redis.RedisCache;
//import com.qujia.common.enums.BusinessType;
//import com.qujia.common.utils.SecurityUtils;
//import com.qujia.common.utils.StringUtils;
//import com.qujia.coupon.domain.*;
//import com.qujia.coupon.domain.cancel.CancelCouponDto;
//import com.qujia.coupon.domain.cancel.CouponInfoVO;
//import com.qujia.coupon.service.*;
//import com.qujia.station.domain.Station;
//import com.qujia.station.enums.CouponNumEnum;
//import com.qujia.station.service.CancelCouponService;
//import com.qujia.station.service.IStationService;
//import com.qujia.system.domain.SysOil;
//import com.qujia.system.domain.SysStationUser;
//import com.qujia.system.service.ISysEnterpriseUserService;
//import com.qujia.system.service.ISysOilService;
//import com.qujia.system.service.ISysStationUserService;
//import com.qujia.system.service.impl.SysDeptServiceImpl;
//import io.swagger.annotations.Api;
//import io.swagger.annotations.ApiOperation;
//import io.swagger.annotations.ApiParam;
//import org.apache.poi.ss.usermodel.Workbook;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.http.ResponseEntity;
//import org.springframework.transaction.annotation.Transactional;
//import org.springframework.web.bind.annotation.*;
//
//import javax.imageio.ImageIO;
//import javax.servlet.http.HttpServletResponse;
//import javax.validation.Valid;
//import java.awt.image.BufferedImage;
//import java.io.ByteArrayOutputStream;
//import java.io.IOException;
//import java.math.BigDecimal;
//import java.net.URLEncoder;
//import java.text.ParseException;
//import java.text.SimpleDateFormat;
//import java.util.*;
//import java.util.concurrent.TimeUnit;
//
///**
// * @Auther: LogicQin
// * @Date: 2023/6/21 15:16
// * @Description:用来处理新的优惠券创建的接口
// */
//@Api(tags = "优惠券创建控制器")
//@RestController
//@RequestMapping("/coupon/creation")
//public class CouponCreationController extends BaseController {
//    @Autowired
//    private ICouponInfoService couponInfoService;
//    @Autowired
//    private IStationService stationService;
//    @Autowired
//    private ISysEnterpriseUserService sysEnterpriseUserService;
//    @Autowired
//    private ISysStationUserService sysStationUserService;
//    @Autowired
//    private ICouponIssueService couponIssueService;
//    @Autowired
//    private ICouponIssueRelationService couponIssueRelationService;
//    @Autowired
//    private SysDeptServiceImpl sysDeptService;
//    @Autowired
//    private ISysOilService oilService;
//    @Autowired
//    private IIssueStationService iIssueStationService;
//    @Autowired
//    private IIssueOilService iIssueOilService;
//    @Autowired
//    private RedisCache redisCache;
//    @Autowired
//    private CancelCouponService cancelCouponService;
//
//    /**
//     * 新增优惠劵
//     */
//    @Log(title = "优惠劵", businessType = BusinessType.INSERT)
//    @ApiOperation(value = "创建优惠劵", httpMethod = "POST")
//    @PostMapping("/creation")
//    @Transactional
//    public AjaxResult add(@RequestBody CouponCreation couponInfo) {
//        try {
//            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//            LoginUser currentUser = SecurityUtils.getLoginUser();
//            couponInfo.setUseCouponNum(null);
//            couponInfo.setGetCouponNum(null);
//            if (!"1".equals(currentUser.getUser().getUserLevel())) {
//                return AjaxResult.error("权限不足");
//            }
//
//            logger.info("创建优惠券 入参：{}",couponInfo);
//            if (couponInfo.getCouponNum() == 0){
//                couponInfo.setCouponNum(CouponNumEnum.MAX.getValue());
//            }
//
//            couponInfo.setEnterpriseId(currentUser.getUser().getEnterpriseId());
//            couponInfo.setCreateBy(String.valueOf(currentUser.getUser().getUserId()));
//            if (couponInfo != null && couponInfo.getEffectiveTime() != null && couponInfo.getEffectiveTime().size() > 0) {
//                String start = couponInfo.getEffectiveTime().get(0);
//                String end = couponInfo.getEffectiveTime().get(1);
//                if (start != null && start != "") {
//                    couponInfo.setEffectiveTimeStart(dateFormat.parse(start));
//                }
//                if (end != null && end != "") {
//                    couponInfo.setEffectiveTimeEnd(dateFormat.parse(end));
//                }
//            }
//            if (couponInfo != null && couponInfo.getAllDate() != null && couponInfo.getAllDate().size() > 0) {
//                String start = couponInfo.getAllDate().get(0);
//                String end = couponInfo.getAllDate().get(1);
//                if (start != null && start != "") {
//                    couponInfo.setStartDate(dateFormat.parse(start));
//                }
//                if (end != null && end != "") {
//                    couponInfo.setEndDate(dateFormat.parse(end));
//                }
//            }
//            long currentTime = System.currentTimeMillis();
//
//// 获取结束时间的毫秒级时间戳
//            Date endDate = couponInfo.getEndDate();
//            long endTime = endDate.getTime();
//
//// 检查结束时间是否在当前时间之前
//            if (endTime < currentTime) {
//                return AjaxResult.error("发放结束时间不能在当前时间之前");
//
//
//            }
//
////            一连串数据校验
//            if (couponInfo != null && couponInfo.getCycleDaysList() != null && couponInfo.getCycleDaysList().size() > 0) {
//                String cycleDays = String.join(",", couponInfo.getCycleDaysList());
//                couponInfo.setCycleDays(cycleDays);
//            }
//            if (couponInfo != null && couponInfo.getAppointedDaysList() != null && couponInfo.getAppointedDaysList().size() > 0) {
//                String appointedDays = String.join(",", couponInfo.getAppointedDaysList());
//                couponInfo.setAppointedDays(appointedDays);
//            }
//            if (couponInfo != null && couponInfo.getVerificationList() != null && couponInfo.getVerificationList().size() > 0) {
//                String verification = StringUtils.join(couponInfo.getVerificationList(), ",");
//                couponInfo.setVerification(verification);
//            }
//            if (couponInfo != null && couponInfo.getEffectiveTimeType() != null && couponInfo.getEffectiveTimeType().equals("1")) {
//                if (couponInfo.getEffectiveTimeEnd().before(couponInfo.getEffectiveTimeStart())) {
//                    return AjaxResult.error("截止时间不得小于开始时间");
//                }
//                if(couponInfo.getEffectiveTimeEnd().before(endDate)){
//                    return AjaxResult.error("结束时间不能小于优惠券发放时间的结束时间");
//                }
//                if (couponInfo.getEffectiveTimeEnd().before(new Date())) {
//                    return AjaxResult.error("当前优惠券的使用有效期已经超期");
//                }
//            }
//
//        } catch (ParseException e) {
//            e.printStackTrace();
//        }
//        if (couponInfo.getCouponType().equals("4")){
//            couponInfo.setCouponThresholdAmt(BigDecimal.valueOf(0));
//        }
////注:最小门槛为couponThresholdAmt字段，新增的时候做了处理
//        int a = couponInfoService.insertCouponCreation(couponInfo);
////        构建新的CouponIssue来一次就可以发放优惠券
//        CouponIssue couponIssue = couponIssueService.createNewCouponIssue(couponInfo);
//        int i = couponIssueService.insertCouponIssue(couponIssue);
//
//        CouponIssueRelation issueRetail = new CouponIssueRelation();
//
//        couponInfo.setEditFlag("1");
////            i = couponInfoService.updateCouponInfo(couponInfo);
//        issueRetail.setIssueId(couponIssue.getId());
//        String couponIdString = couponInfo.getId(); // couponId是String类型
//
//// 将String转换为Long
//        Long couponIdLong = null;
//        if (couponIdString != null && !couponIdString.isEmpty()) {
//            couponIdLong = Long.parseLong(couponIdString);
//        }
//        issueRetail.setCouponId(couponIdLong);
////            issueRetail.setThresholdAmt(threshold.getValue());
//        LoginUser currentUser = SecurityUtils.getLoginUser();
//        issueRetail.setCreateBy(String.valueOf(currentUser.getUser().getUserId()));
//        int b = couponIssueRelationService.insertCouponIssueRelation(issueRetail);
//
//        if (a > 0 && i > 0) {
//            // 处理与油品相关的信息
//            if (couponInfo != null && couponInfo.getOilIdLists() != null && couponInfo.getOilIdLists().size() > 0) {
//                for (SysOil sysOil : couponInfo.getOilIdLists()) {
//                    IssueOilRelations issueOilRelations = new IssueOilRelations();
//                    issueOilRelations.setIssueId(couponIssue.getId());
//                    issueOilRelations.setOilId(sysOil.getOilId());
//                    iIssueOilService.insertIssueOilRelations(issueOilRelations);
//                }
//            }
//
//            // 处理与加油站相关的信息
//            if (couponInfo != null && couponInfo.getStationId() != null) {
////                全部油企传个0
//                if (couponInfo.getStationId().equals(0L)) {
//                    Station station = new Station();
//                    station.setEnterpriseId(couponInfo.getEnterpriseId());
//                    List<Station> stations = stationService.selectStationList(station);
//                    for (Station stationobj : stations) {
//                        IssueStationRelations issueStationRelations = new IssueStationRelations();
//                        issueStationRelations.setIssueId(couponIssue.getId());
//                        issueStationRelations.setStationId(stationobj.getStationId());
//                        iIssueStationService.insertIssueStationRelations(issueStationRelations);
//                    }
//
//                } else {
//                    IssueStationRelations issueStationRelations = new IssueStationRelations();
//                    issueStationRelations.setIssueId(couponIssue.getId());
//                    issueStationRelations.setStationId(couponInfo.getStationId());
//                    iIssueStationService.insertIssueStationRelations(issueStationRelations);
//                }
//
//            }
//
//        } else {
//            throw new RuntimeException("新增操作失败，事务回滚");
//        }
//        String couponId = couponIssue.getId(); // 获取优惠券的 IDlistByLogin
//        long currentTime = System.currentTimeMillis();
//        long expireMillis = 0;
//        int expireSeconds = 0;
//
//        if (couponIssue.getEndDate() != null) {
//            expireMillis = couponIssue.getEndDate().getTime() - currentTime;
//            expireSeconds = (int) (expireMillis / 1000);
//            redisCache.setCacheObject("coupon:" + couponId, "优惠券信息", expireSeconds, TimeUnit.SECONDS);
//        }
//        return AjaxResult.success();
//    }
//
//    /**
//     * 删除优惠劵
//     */
//    @Log(title = "优惠劵", businessType = BusinessType.DELETE)
//    @ApiOperation(value = "删除优惠劵", httpMethod = "POST")
//    @PostMapping("/delete")
//    @Transactional
//    public AjaxResult delete(@RequestBody Long[] couponIssueIds) {
//        try {
//            LoginUser currentUser = SecurityUtils.getLoginUser();
//            if (!"1".equals(currentUser.getUser().getUserLevel())) {
//                return AjaxResult.error("权限不足");
//            }
//
//            Integer[] couponIds = new Integer[couponIssueIds.length];
//            for (int i = 0; i < couponIssueIds.length; i++) {
//                long couponIssueId = couponIssueIds[i];
//                CouponIssue CouponIssuen = couponIssueService.selectIssueById(couponIssueId);
//                if (CouponIssuen.getStatus().equals("1")) {
//                    return AjaxResult.error("生效中的优惠券禁止删除");
//                }
//                int a = couponIssueService.getCouponActivityByIssueId(couponIssueId);
//                if (a > 0) {
//                    return AjaxResult.error("绑定了优惠券活动的优惠券禁止删除");
//                }
//
//            }
//            for (int i = 0; i < couponIssueIds.length; i++) {
//                long couponIssueId = couponIssueIds[i];
//                Integer convertedId = Optional.ofNullable(couponIssueService.getCouponInfoIdByIssueId(couponIssueId)).orElse(0);
//                couponIssueService.deleteIssueOilRelationsByIssueId(couponIssueId);
//                couponIds[i] = convertedId; // 在convertedId为null时，赋值为0或其他默认值
//            }
//            // 删除优惠劵
//            int deletedCouponCount = couponInfoService.deleteCouponInfoByCouponIds(couponIds);
//            if (deletedCouponCount > 0) {
//                // 删除优惠劵发放关系
//                int deletedIssueCount = couponIssueService.deleteCouponIssueByIssueIds(couponIssueIds);
//                if (deletedIssueCount > 0) {
//                    // 删除与油品相关的信息
//                    iIssueOilService.deleteIssueOilRelationsByIssueIds(couponIssueIds);
//                    // 删除与加油站相关的信息
//                    iIssueStationService.deleteIssueStationRelationsByIssueIds(couponIssueIds);
//                    return AjaxResult.success();
//                } else {
//                    throw new RuntimeException("删除优惠劵发放关系失败，事务回滚");
//                }
//            } else {
//                return AjaxResult.error("优惠劵已删除，请勿重复删除");
//
//            }
//        } catch (Exception e) {
//            e.printStackTrace();
//            throw new RuntimeException("删除优惠劵发生异常，事务回滚");
//        }
//    }
//
//    /**
//     * 修改优惠劵
//     */
//    @Log(title = "优惠劵", businessType = BusinessType.UPDATE)
//    @ApiOperation(value = "修改优惠劵", httpMethod = "PUT")
//    @PutMapping("/modify")
//    @Transactional
//    public AjaxResult modify(@RequestBody CouponCreation couponInfo) {
//
//        try {
//            couponInfo.setUseCouponNum(null);
//            couponInfo.setGetCouponNum(null);
//            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//            LoginUser currentUser = SecurityUtils.getLoginUser();
//            if (!"1".equals(currentUser.getUser().getUserLevel())) {
//                return AjaxResult.error("权限不足");
//            }
//            CouponIssue couponIssue = couponIssueService.selectCouponIssueById(couponInfo.getId());
//            if (!couponIssue.getStatus().equals("0")) {
//                return AjaxResult.error("只有“待生效”的优惠券才能编辑");
//            }
//
//            logger.info("修改优惠券 入参：{}",couponInfo);
//            if (couponInfo.getCouponNum() == 0){
//                couponInfo.setCouponNum(CouponNumEnum.MAX.getValue());
//            }
//
//            couponInfo.setEnterpriseId(currentUser.getUser().getEnterpriseId());
//            couponInfo.setUpdateBy(String.valueOf(currentUser.getUser().getUserId()));
//            if (couponInfo != null && couponInfo.getEffectiveTime() != null && couponInfo.getEffectiveTime().size() > 0) {
//                String start = couponInfo.getEffectiveTime().get(0);
//                String end = couponInfo.getEffectiveTime().get(1);
//                if (start != null && start != "") {
//                    couponInfo.setEffectiveTimeStart(dateFormat.parse(start));
//                }
//                if (end != null && end != "") {
//                    couponInfo.setEffectiveTimeEnd(dateFormat.parse(end));
//                }
//            }
//            if (couponInfo != null && couponInfo.getAllDate() != null && couponInfo.getAllDate().size() > 0) {
//                String start = couponInfo.getAllDate().get(0);
//                String end = couponInfo.getAllDate().get(1);
//                if (start != null && start != "") {
//                    couponInfo.setStartDate(dateFormat.parse(start));
//                }
//                if (end != null && end != "") {
//                    couponInfo.setEndDate(dateFormat.parse(end));
//                }
//            }
//            long currentTime = System.currentTimeMillis();
//
//// 获取结束时间的毫秒级时间戳
//            Date endDate = couponInfo.getEndDate();
//            long endTime = endDate.getTime();
//
//// 检查结束时间是否在当前时间之前
//            if (endTime < currentTime) {
//                return AjaxResult.error("发放结束时间不能在当前时间之前");
//
//
//            }
//            // 一连串数据校验
//            if (couponInfo != null && couponInfo.getCycleDaysList() != null && couponInfo.getCycleDaysList().size() > 0) {
//                String cycleDays = String.join(",", couponInfo.getCycleDaysList());
//                couponInfo.setCycleDays(cycleDays);
//            }
//            if (couponInfo != null && couponInfo.getAppointedDaysList() != null && couponInfo.getAppointedDaysList().size() > 0) {
//                String appointedDays = String.join(",", couponInfo.getAppointedDaysList());
//                couponInfo.setAppointedDays(appointedDays);
//            }
//            if (couponInfo != null && couponInfo.getVerificationList() != null && couponInfo.getVerificationList().size() > 0) {
//                String verification = StringUtils.join(couponInfo.getVerificationList(), ",");
//                couponInfo.setVerification(verification);
//            }
//            if (couponInfo != null && couponInfo.getEffectiveTimeType() != null && couponInfo.getEffectiveTimeType().equals("1")) {
//                if (couponInfo.getEffectiveTimeEnd().before(couponInfo.getEffectiveTimeStart())) {
//                    return AjaxResult.error("截止时间不得小于开始时间");
//                }
//                if(couponInfo.getEffectiveTimeEnd().before(endDate)){
//                    return AjaxResult.error("结束时间不能小于优惠券发放时间的结束时间");
//                }
//                if (couponInfo.getEffectiveTimeEnd().before(new Date())) {
//                    return AjaxResult.error("当前优惠券的使用有效期已经超期");
//                }
//            }
//        } catch (ParseException e) {
//            e.printStackTrace();
//        }
//
//        int a = couponInfoService.updateCouponCreation(couponInfo);
//        CouponIssue couponIssue = couponIssueService.updateNewCouponIssue(couponInfo);
//        int i = couponIssueService.updateCouponIssue(couponIssue);
//
//        String couponId = couponIssue.getId(); // 获取优惠券的 IDlistByLogin
//        redisCache.deleteObject("coupon:" + couponId);
//
//        long currentTime = System.currentTimeMillis();
//        long expireMillis = 0;
//        int expireSeconds = 0;
//
//        if (couponIssue.getEndDate() != null) {
//            expireMillis = couponIssue.getEndDate().getTime() - currentTime;
//            expireSeconds = (int) (expireMillis / 1000);
//            redisCache.setCacheObject("coupon:" + couponId, "优惠券信息", expireSeconds, TimeUnit.SECONDS);
//        }
//        if (a > 0) {
//            // 处理与油品相关的信息
//            if (couponInfo != null && couponInfo.getOilIdLists() != null && couponInfo.getOilIdLists().size() > 0) {
//                // 删除原有的关联关系
//                iIssueOilService.deleteIssueOilRelationsByIssueId(couponInfo.getId());
//                // 重新建立关联关系
//                for (SysOil sysOil : couponInfo.getOilIdLists()) {
//                    IssueOilRelations issueOilRelations = new IssueOilRelations();
//                    issueOilRelations.setIssueId(couponInfo.getId());
//                    issueOilRelations.setOilId(sysOil.getOilId());
//                    iIssueOilService.insertIssueOilRelations(issueOilRelations);
//                }
//            }
//
//            // 处理与加油站相关的信息
//            if (couponInfo != null && couponInfo.getStationId() != null) {
//                // 删除原有的关联关系
//                iIssueStationService.deleteIssueStationRelationsByIssueId(couponInfo.getId());
//                // 重新建立关联关系
//                if (couponInfo.getStationId().equals(0L)) {
//                    Station station = new Station();
//                    station.setEnterpriseId(couponInfo.getEnterpriseId());
//                    List<Station> stations = stationService.selectStationList(station);
//                    for (Station stationobj : stations) {
//                        IssueStationRelations issueStationRelations = new IssueStationRelations();
//                        issueStationRelations.setIssueId(couponInfo.getId());
//                        issueStationRelations.setStationId(stationobj.getStationId());
//                        iIssueStationService.insertIssueStationRelations(issueStationRelations);
//                    }
//                } else {
//                    IssueStationRelations issueStationRelations = new IssueStationRelations();
//                    issueStationRelations.setIssueId(couponInfo.getId());
//                    issueStationRelations.setStationId(couponInfo.getStationId());
//                    iIssueStationService.insertIssueStationRelations(issueStationRelations);
//                }
//            }
//            return AjaxResult.success();
//        } else {
//            return AjaxResult.error("修改操作失败");
//        }
//    }
//
//    /**
//     * 查询优惠劵发放方式列表/list
//     */
//    @GetMapping("/list")
//    @ApiOperation(value = "查询优惠劵列表", httpMethod = "GET")
//    public TableDataInfo list(CouponCreation couponIssue) {
//        LoginUser currentUser = SecurityUtils.getLoginUser();
//        if (StringUtils.isNotEmpty(currentUser.getUser().getUserLevel())&&!"1".equals(currentUser.getUser().getUserLevel())) {
//            return getDataTable(new ArrayList<>());
//        } else {
//            couponIssue.setEnterpriseId(currentUser.getUser().getEnterpriseId());
//        }
//        //couponIssue.setStationId(currentUser.getUser().getDeptId());
//        startPage();
////        List<CouponIssue> list2 = couponIssueService.selectCouponIssueList(couponIssue);
//        List<CouponCreation> list = couponIssueService.selectCouponIssueListByCreation(couponIssue);
//        if (list != null && list.size() > 0) {
//            for (CouponCreation issue : list) {
//                //将原有分类转化为集合
//                if (issue != null && issue.getShowId() != null) {
//                    issue.setShowIdList(Arrays.asList(issue.getShowId().split(",")));
//                }
//                if (issue != null && issue.getMemberLevel() != null) {
//                    issue.setMemberLevelList(Arrays.asList(issue.getMemberLevel().split(",")));
//                }
//                if (issue != null && issue.getPaymentMethod() != null) {
//                    issue.setPaymentMethodList(Arrays.asList(issue.getPaymentMethod().split(",")));
//                }
//                if (issue != null && issue.getMemberTags() != null) {
//                    issue.setMemberTagsList(Arrays.asList(issue.getMemberTags().split(",")));
//                }
//
//            }
//        }
//        return getDataTable(list);
//    }
//
//    /**
//     * 更新优惠券状态
//     *
//     * @param issueId 发行ID
//     * @param status  状态值（1：启用，0：停用）
//     * @return 更新结果
//     */
//    @ApiOperation("更新优惠券状态")
//    @PutMapping("/status/{issueId}")
//    public ResponseEntity<String> updateCouponStatus(
//            @ApiParam(value = "发行ID", required = true) @PathVariable("issueId") Long issueId,
//            @ApiParam(value = "状态值（1：启用，0：停用）", required = true) @RequestParam("status") String status) {
//        couponIssueService.updateCouponStatus(issueId, status);
//        return ResponseEntity.ok("优惠券状态更新成功。");
//    }
//
//    private static final String CHARSET = "utf-8";
//    private static final String FORMAT_NAME = "PNG";
//    // 二维码尺寸
//    private static final int QRCODE_SIZE = 300;
//    // LOGO宽度
//    private static final int WIDTH = 60;
//    // LOGO高度
//    private static final int HEIGHT = 60;
//
//    private static BufferedImage createImage(String content, boolean needCompress) throws Exception {
//        // 创建一个 Hashtable 对象用于存储生成二维码时的参数配置
//        Hashtable<EncodeHintType, Object> hints = new Hashtable<>();
//        hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H); // 设置纠错级别为 H
//        hints.put(EncodeHintType.CHARACTER_SET, CHARSET); // 设置字符集编码
//        hints.put(EncodeHintType.MARGIN, 1); // 设置二维码边距为 1
//
//        // 使用 MultiFormatWriter 类的 encode() 方法生成 BitMatrix 对象，表示二维码的位矩阵
//        BitMatrix bitMatrix = new MultiFormatWriter().encode(
//                content, BarcodeFormat.QR_CODE, QRCODE_SIZE, QRCODE_SIZE, hints);
//
//        int width = bitMatrix.getWidth(); // 获取位矩阵的宽度
//        int height = bitMatrix.getHeight(); // 获取位矩阵的高度
//
//        // 创建一个 BufferedImage 对象，表示最终生成的二维码图像
//        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
//
//        // 将位矩阵的值映射到图像的像素值上，生成最终的二维码图像
//        for (int x = 0; x < width; x++) {
//            for (int y = 0; y < height; y++) {
//                // 设置图像像素的 RGB 值，根据位矩阵的值决定是黑色还是白色
//                image.setRGB(x, y, bitMatrix.get(x, y) ? 0xFF000000 : 0xFFFFFFFF);
//            }
//        }
//
//        return image;
//    }
//
//
//    @GetMapping("/export")
//    public void exportCoupons(@RequestParam("ids") List<String> ids, HttpServletResponse response) {
//        // 获取需要导出的数据
//        List<CouponExport> couponList = couponIssueService.getCouponIssueListByIds(ids);
//        // 处理二维码并赋值给字段
//        for (CouponExport coupon : couponList) {
//            try {
//                String qrCodeText = "https://example.com/coupons/" + coupon.getEncodedId();
////                String qrCodeBase64 = generateQRCodeBase64(qrCodeText);
////                coupon.setEncodedId(qrCodeBase64);
//
//                BufferedImage image = createImage(qrCodeText, false);
//                ByteArrayOutputStream baos = new ByteArrayOutputStream();
//                ImageIO.write(image, "png", baos);
//                coupon.setImgFile(baos.toByteArray());
//            } catch (Exception e) {
//                // 处理异常
//                e.printStackTrace();
//                // 在这里处理异常，例如删除该coupon或者跳过
//                continue;
//            }
//        }
//        //excel参数
//        Map<String, Object> excelMap = new HashMap<>();
//        ExportParams params = new ExportParams(
//                "doc/模板名称", "xlsx");
//        Workbook workBook = null;
//        try {
//            excelMap.put("startDate", "2022-01-01");
//            excelMap.put("endDate", "2022-02-01");
//            workBook = ExcelExportUtil.exportExcel(params, CouponExport.class, couponList);
//            response.setContentType("application/octet-stream");
//            response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode("template.xlsx", "UTF-8"));
//            workBook.write(response.getOutputStream());
//            response.flushBuffer();
//        } catch (Exception e) {
//            e.printStackTrace();
//            throw new RuntimeException("导出异常，详细信息: " + e.getMessage());
//        } finally {
//            if (workBook != null) {
//                try {
//                    workBook.close();
//                } catch (IOException e) {
//                    e.printStackTrace();
//                }
//            }
//        }
//
//    }
//
//    // 生成二维码的方法，请根据实际情况进行实现
//    private String generateQRCodeBase64(String text) {
//        // 实现逻辑
//        return "";
//    }
//
//
//    /**
//     * 获取优惠劵发放方式详细信息
//     */
//    @ApiOperation(value = "优惠券详情", httpMethod = "GET")
//    @GetMapping(value = "/details/{id}")
//    public AjaxResult getInfo(@PathVariable("id") String id) {
//        //查询优惠劵发放方式
//        CouponIssue couponIssue = couponIssueService.selectCouponIssueById(id);
//        if (couponIssue == null) {
//            return AjaxResult.error("未查询到对应的优惠卷！");
//        }
//        //将原有分类转化为集合
//        if (couponIssue != null && couponIssue.getShowId() != null) {
//            couponIssue.setShowIdList(Arrays.asList(couponIssue.getShowId().split(",")));
//        }
//        if (couponIssue != null && couponIssue.getMemberLevel() != null) {
//            couponIssue.setMemberLevelList(Arrays.asList(couponIssue.getMemberLevel().split(",")));
//        }
//        if (couponIssue != null && couponIssue.getPaymentMethod() != null) {
//            couponIssue.setPaymentMethodList(Arrays.asList(couponIssue.getPaymentMethod().split(",")));
//        }
//        if (couponIssue != null && couponIssue.getMemberTags() != null) {
//            couponIssue.setMemberTagsList(Arrays.asList(couponIssue.getMemberTags().split(",")));
//        }
//        //将油品的关联信息查询出来
//        List<SysOil> oils = new ArrayList<>();
//        IssueOilRelations issueOilRelations = new IssueOilRelations();
//        issueOilRelations.setIssueId(couponIssue.getId());
//        List<IssueOilRelations> issueOilRelations1 = iIssueOilService.selectIssueOilRelationsList(issueOilRelations);
//        for (IssueOilRelations issueOilRelations2 : issueOilRelations1) {
//            SysOil oil = oilService.selectSysOilById(issueOilRelations2.getOilId());
//            oils.add(oil);
//        }
//        couponIssue.setOilIdLists(oils);
//
//        //查询关联的油站信息
//        List<SysStationUser> stationUsers = new ArrayList<>();
//        IssueStationRelations issueStationRelations = new IssueStationRelations();
//        issueStationRelations.setIssueId(couponIssue.getId());
//        List<IssueStationRelations> issueStationRelationsList = iIssueStationService.selectIssueStationRelationsList(issueStationRelations);
//        for (IssueStationRelations issueStationRelations1 : issueStationRelationsList) {
//            SysStationUser sysStationUser = sysStationUserService.selectSysStationUserById(issueStationRelations1.getStationId());
//            stationUsers.add(sysStationUser);
//        }
//
//        couponIssue.setStationLists(stationUsers);
//        //获取关联的优惠卷信息
//        List<CouponInfo> couponInfoList = new ArrayList<>();
//        CouponIssueRelation couponIssueRelation2 = new CouponIssueRelation();
//        couponIssueRelation2.setIssueId(couponIssue.getId());
//        List<CouponIssueRelation> couponIssueRelationList = couponIssueRelationService.selectCouponIssueRelationList(couponIssueRelation2);
//        for (CouponIssueRelation couponIssueRelation1 : couponIssueRelationList) {
//            CouponInfo couponInfo = couponInfoService.selectCouponInfoById(Integer.parseInt(couponIssueRelation1.getCouponId() + ""));
//            couponInfoList.add(couponInfo);
//        }
//        couponIssue.setCouponList(couponInfoList);
//
//        CouponIssueRelation couponIssueRelation = new CouponIssueRelation();
//        couponIssueRelation.setIssueId(couponIssue.getId());
//        //添加发放方式的信息和优惠卷关联表
//        List<CouponIssueRelation> detailList = couponIssueRelationService.selectCouponIssueRelationList(couponIssueRelation);
//        List<Integer> idlist = couponIssueRelationService.selectCouponIdList(couponIssueRelation);
//        List<CouponInfo> couponInfos = new ArrayList<>();
//        for (int i = 0; i < idlist.size() - 1; i++) {
//            for (int j = idlist.size() - 1; j > i; j--) {
//                if (idlist.get(i).equals(idlist.get(j)))
//                    idlist.remove(j);
//            }
//        }
//        if (detailList != null && detailList.size() > 0) {
//            for (Integer data : idlist) {
//                couponInfos.add(couponInfoService.selectCouponInfoById(Integer.valueOf(data)));
//            }
//            couponIssue.setCouponList(couponInfos);
//
//            couponIssue.setCouponIssueRelationList(idlist);
//        }
//
//        CouponIssueRelation couponIssueRelation1 = new CouponIssueRelation();
//        couponIssueRelation1.setIssueId(couponIssue.getId());
//        List<CouponIssueRelation> couponIssueRelations = couponIssueRelationService.selectCouponInfos(couponIssueRelation1);
//        //根据状态来拆分对应的优惠卷的信息，赋值到对应的阶梯直降
//        if ("ladder".equals(couponIssue.getThresholdType())) {
//            List<Threshold> thresholds = new ArrayList<>();
//            if (couponIssueRelations != null && couponIssueRelations.size() > 0) {
//                for (CouponIssueRelation couponIssueRelation3 : couponIssueRelations) {
//                    List<String> couponids = Arrays.asList(couponIssueRelation3.getInfos().split(","));
//                    if (couponids != null && couponids.size() > 0) {
//                        //couponids.remove(couponids.size() - 1);
//                        Threshold threshold = new Threshold();
//                        threshold.setCouponList(couponids);
//                        threshold.setValue(couponIssueRelation3.getThresholdAmt());
//                        thresholds.add(threshold);
//                    }
//                }
//            }
//            couponIssue.setThresholdLadder(thresholds);
//        }
//        CouponCreation couponCreation = couponIssueService.fullCouponCreationForCouponIssue(couponIssue);
//
//        if (couponInfoList != null && !couponInfoList.isEmpty()) {
//            couponCreation = couponIssueService.fullCouponCreationForCouponInfo(couponCreation, couponInfoList.get(0));
//
//        }
//        List<SysStationUser> stationLists = couponIssue.getStationLists();
//        if (stationLists != null && !stationLists.isEmpty()) {
//            if (stationLists.size() > 1) {
//                couponCreation.setStationId(0L);
//            } else {
//                couponCreation.setStationId(stationLists.get(0).getStationId());
//            }
//        }
//
//        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//        String startDateStr = dateFormat.format(couponCreation.getStartDate());
//        String endDateStr = dateFormat.format(couponCreation.getEndDate());
//        // 将转换后的字符串设置为allDate列表的值
//        List<String> allDate = new ArrayList<>();
//        allDate.add(startDateStr);
//        allDate.add(endDateStr);
//        couponCreation.setAllDate(allDate);
//        if(couponCreation.getEffectiveTimeType().equals("1")){
//            String ffectiveTimeStart = dateFormat.format(couponCreation.getEffectiveTimeStart());
//            String ffectiveTimeEnd = dateFormat.format(couponCreation.getEffectiveTimeEnd());
//            // 将转换后的字符串设置为allDate列表的值
//            List<String> ffectiveTime = new ArrayList<>();
//            ffectiveTime.add(ffectiveTimeStart);
//            ffectiveTime.add(ffectiveTimeEnd);
//            couponCreation.setEffectiveTime(ffectiveTime);
//        }
//        couponCreation.setUseCouponNum(null);
//        couponCreation.setGetCouponNum(null);
//        //如果是最大值  回传 0
//        if (couponCreation.getCouponNum().equals(Integer.MAX_VALUE) || couponCreation.getCouponNum().equals(CouponNumEnum.MAX.getValue())){
//            couponCreation.setCouponNum(0);
//        }
//
//        return AjaxResult.success(couponCreation);
//    }
//
//
//    /**
//     * 获取优惠劵发放方式详细信息
//     */
//    @ApiOperation(value = "优惠券复制模板", httpMethod = "GET")
//    @GetMapping(value = "/getInfoForCopy/{id}")
//    public AjaxResult getInfoForCopy(@PathVariable("id") String id) {
//        //查询优惠劵发放方式
//        CouponIssue couponIssue = couponIssueService.selectCouponIssueById(id);
//        if (couponIssue == null) {
//            return AjaxResult.error("未查询到对应的优惠卷！");
//        }
//        //将原有分类转化为集合
//        if (couponIssue != null && couponIssue.getShowId() != null) {
//            couponIssue.setShowIdList(Arrays.asList(couponIssue.getShowId().split(",")));
//        }
//        if (couponIssue != null && couponIssue.getMemberLevel() != null) {
//            couponIssue.setMemberLevelList(Arrays.asList(couponIssue.getMemberLevel().split(",")));
//        }
//        if (couponIssue != null && couponIssue.getPaymentMethod() != null) {
//            couponIssue.setPaymentMethodList(Arrays.asList(couponIssue.getPaymentMethod().split(",")));
//        }
//        if (couponIssue != null && couponIssue.getMemberTags() != null) {
//            couponIssue.setMemberTagsList(Arrays.asList(couponIssue.getMemberTags().split(",")));
//        }
//        //将油品的关联信息查询出来
//        List<SysOil> oils = new ArrayList<>();
//        IssueOilRelations issueOilRelations = new IssueOilRelations();
//        issueOilRelations.setIssueId(couponIssue.getId());
//        List<IssueOilRelations> issueOilRelations1 = iIssueOilService.selectIssueOilRelationsList(issueOilRelations);
//        for (IssueOilRelations issueOilRelations2 : issueOilRelations1) {
//            SysOil oil = oilService.selectSysOilById(issueOilRelations2.getOilId());
//            oils.add(oil);
//        }
//        couponIssue.setOilIdLists(oils);
//
//        //查询关联的油站信息
//        List<SysStationUser> stationUsers = new ArrayList<>();
//        IssueStationRelations issueStationRelations = new IssueStationRelations();
//        issueStationRelations.setIssueId(couponIssue.getId());
//        List<IssueStationRelations> issueStationRelationsList = iIssueStationService.selectIssueStationRelationsList(issueStationRelations);
//        for (IssueStationRelations issueStationRelations1 : issueStationRelationsList) {
//            SysStationUser sysStationUser = sysStationUserService.selectSysStationUserById(issueStationRelations1.getStationId());
//            stationUsers.add(sysStationUser);
//        }
//
//        couponIssue.setStationLists(stationUsers);
//        //获取关联的优惠卷信息
//        List<CouponInfo> couponInfoList = new ArrayList<>();
//        CouponIssueRelation couponIssueRelation2 = new CouponIssueRelation();
//        couponIssueRelation2.setIssueId(couponIssue.getId());
//        List<CouponIssueRelation> couponIssueRelationList = couponIssueRelationService.selectCouponIssueRelationList(couponIssueRelation2);
//        for (CouponIssueRelation couponIssueRelation1 : couponIssueRelationList) {
//            CouponInfo couponInfo = couponInfoService.selectCouponInfoById(Integer.parseInt(couponIssueRelation1.getCouponId() + ""));
//            couponInfoList.add(couponInfo);
//        }
//        couponIssue.setCouponList(couponInfoList);
//
//        CouponIssueRelation couponIssueRelation = new CouponIssueRelation();
//        couponIssueRelation.setIssueId(couponIssue.getId());
//        //添加发放方式的信息和优惠卷关联表
//        List<CouponIssueRelation> detailList = couponIssueRelationService.selectCouponIssueRelationList(couponIssueRelation);
//        List<Integer> idlist = couponIssueRelationService.selectCouponIdList(couponIssueRelation);
//        List<CouponInfo> couponInfos = new ArrayList<>();
//        for (int i = 0; i < idlist.size() - 1; i++) {
//            for (int j = idlist.size() - 1; j > i; j--) {
//                if (idlist.get(i).equals(idlist.get(j)))
//                    idlist.remove(j);
//            }
//        }
//        if (detailList != null && detailList.size() > 0) {
//            for (Integer data : idlist) {
//                couponInfos.add(couponInfoService.selectCouponInfoById(Integer.valueOf(data)));
//            }
//            couponIssue.setCouponList(couponInfos);
//
//            couponIssue.setCouponIssueRelationList(idlist);
//        }
//
//        CouponIssueRelation couponIssueRelation1 = new CouponIssueRelation();
//        couponIssueRelation1.setIssueId(couponIssue.getId());
//        List<CouponIssueRelation> couponIssueRelations = couponIssueRelationService.selectCouponInfos(couponIssueRelation1);
//        //根据状态来拆分对应的优惠卷的信息，赋值到对应的阶梯直降
//        if ("ladder".equals(couponIssue.getThresholdType())) {
//            List<Threshold> thresholds = new ArrayList<>();
//            if (couponIssueRelations != null && couponIssueRelations.size() > 0) {
//                for (CouponIssueRelation couponIssueRelation3 : couponIssueRelations) {
//                    List<String> couponids = Arrays.asList(couponIssueRelation3.getInfos().split(","));
//                    if (couponids != null && couponids.size() > 0) {
//                        //couponids.remove(couponids.size() - 1);
//                        Threshold threshold = new Threshold();
//                        threshold.setCouponList(couponids);
//                        threshold.setValue(couponIssueRelation3.getThresholdAmt());
//                        thresholds.add(threshold);
//                    }
//                }
//            }
//            couponIssue.setThresholdLadder(thresholds);
//        }
//        CouponCreation couponCreation = couponIssueService.fullCouponCreationForCouponIssue(couponIssue);
//
//        if (couponInfoList != null && !couponInfoList.isEmpty()) {
//            couponCreation = couponIssueService.fullCouponCreationForCouponInfo(couponCreation, couponInfoList.get(0));
//
//        }
//        List<SysStationUser> stationLists = couponIssue.getStationLists();
//        if (stationLists != null && !stationLists.isEmpty()) {
//            if (stationLists.size() > 1) {
//                couponCreation.setStationId(0L);
//            } else {
//                couponCreation.setStationId(stationLists.get(0).getStationId());
//            }
//        }
//        couponCreation.setId(null);
//        couponCreation.setCouponId(null);
//        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//        String startDateStr = dateFormat.format(couponCreation.getStartDate());
//        String endDateStr = dateFormat.format(couponCreation.getEndDate());
//        // 将转换后的字符串设置为allDate列表的值
//        List<String> allDate = new ArrayList<>();
//        allDate.add(startDateStr);
//        allDate.add(endDateStr);
//        couponCreation.setAllDate(allDate);
//        if(couponCreation.getEffectiveTimeType().equals("1")){
//            String ffectiveTimeStart = dateFormat.format(couponCreation.getEffectiveTimeStart());
//            String ffectiveTimeEnd = dateFormat.format(couponCreation.getEffectiveTimeEnd());
//            // 将转换后的字符串设置为allDate列表的值
//            List<String> ffectiveTime = new ArrayList<>();
//            ffectiveTime.add(ffectiveTimeStart);
//            ffectiveTime.add(ffectiveTimeEnd);
//            couponCreation.setEffectiveTime(ffectiveTime);
//        }
//        couponCreation.setUseCouponNum(null);
//        couponCreation.setGetCouponNum(null);
//        //如果是最大值  回传 0
//        if (couponCreation.getCouponNum().equals(CouponNumEnum.MAX.getValue()) || couponCreation.getCouponNum().equals(Integer.MAX_VALUE) ){
//            couponCreation.setCouponNum(0);
//        }
//        return AjaxResult.success(couponCreation);
//    }
//    @ApiOperation(value = "扫码核销优惠券", httpMethod = "POST")
//    @PostMapping(value = "/cancelCoupon")
//    @ResponseBody
//    public ResultData<CouponInfoVO> cancelCoupon(@Valid @RequestBody CancelCouponDto cancelCouponDto){
//        logger.info("扫码核销：{}",cancelCouponDto);
//       return cancelCouponService.cancelCoupon(cancelCouponDto);
//    }
//
//}
